
#include "SelectionManager.h"

SelectionManager::SelectionManager(AVDoc avDoc, CString tag, bool updateAlt, AcronymDictionary& acronymDictionary, SelectionExplorer* pSelectionExplorer)
	: TagManager(avDoc, tag, updateAlt, acronymDictionary, false, pSelectionExplorer)
{
	_pSelectionExplorer->GetSelectionRect(_selectionRect);
}

SelectionManager::~SelectionManager(void)
{
}


void SelectionManager::FillTagRegions( PDEText pdeText, vector<TagRegion>& tagRegions)
{
	tagRegions.clear();

	ASInt32 startIndex = 65535;
	ASInt32 endIndex = 0;

	ASInt32 charCount = PDETextGetNumChars(pdeText);

	for(ASInt32 charIndex = 0; charIndex < charCount; ++charIndex)
	{
		ASFixedQuad asFixedQuad;
		PDETextGetQuad (pdeText, kPDETextChar, charIndex, &asFixedQuad );

		ASFixed charX = (asFixedQuad.tl.h + asFixedQuad.tr.h) / 2;
		ASFixed charY = (asFixedQuad.tl.v + asFixedQuad.bl.v) / 2;

		if(	charX >= _selectionRect.left   && charX <= _selectionRect.right &&
			charY >= _selectionRect.bottom && charY <= _selectionRect.top)
		{
			if(startIndex > charIndex) startIndex = charIndex;
			if(endIndex < charIndex) endIndex = charIndex;
		}
	}

	if(startIndex > endIndex) return;

	// Put selected text into acronym dictionary if it is not there
	int acronymIndex = -1;
	if(_updateAlt)
	{
		CString str;
		StringFromPDEText(str, pdeText);
		str = str.Mid(startIndex, endIndex - startIndex + 1);

		acronymIndex = _acronymDictionary.IndexOf(str);
		if (acronymIndex == -1)
		{
			acronymIndex = _acronymDictionary.Add(str);
		}
	}

	//Fill _tagRegions with selected text
	TagRegion tagRegion;
	tagRegion.Offset = startIndex;
	tagRegion.Length = endIndex - startIndex + 1;
	tagRegion.AcronymIndex = acronymIndex;

	tagRegions.push_back(tagRegion);
}